module.exports = function ($resource, $state, $http, $q, $modal, dlq, $timeout) {
	return {
		restrict: 'AE',
		template: require('../views/p_list1.html'),
		replace: true,
		scope: {
			'load' : '=',
			'other': '=',
			'state' : '=',
			'count' : '=',
		},
		link: function (scope, elements, attrs) {

	
			console.log('scope.state');
			console.log(scope.state);

	scope.vm = {
        //'date' : '',
        'options' : {
            format: "YYYY-MM-DD HH:mm",
            locale : 'zh-cn',
            ignoreReadonly : true,
            //showClear: true ,                       
           // clearBtn:true
        }
    };

    scope.vm1 = {
        //'date' : '',
        'options' : {
            format: "YYYY-MM-DD",
            locale : 'zh-cn',
            ignoreReadonly : true,
            //showClear: true ,                       
           // clearBtn:true
        }
    };


    scope.cancel_flag = '0';

var label = {
	'back_type' : ['可退票', '不可退', '只能整单退票'],
	'sms_type' : ['不发短信', '发送短信'],
	'order_num_state' : ['不限制', '平台限制', '公众号限制'],
	'order_limit_type' : ['手机号', '身份证号', 'id'],
	'price_type' : ['有效期价格', '价格日历'],
	'product_attr' : ['', '电子票', '儿童剧', '实物'],
}


scope.label = {
	'take_effect_type_array' : [
		{'name' : '次日生效', 'code' : -1},
		{'name' : '即时生效', 'code' : 0},
		{'name' : '1小时后生效', 'code' : 1},
		{'name' : '2小时后生效', 'code' : 2},
		{'name' : '4小时后生效', 'code' : 4},
		{'name' : '12小时后生效', 'code' : 12},
	],
}


var typeobj = {};
var columnobj = {};

scope.searchform = {};

/* 分页
   * ========================================= */
scope.maxSize = 5;            //最多显示多少个按钮
scope.bigCurrentPage = 1;      //当前页码
scope.itemsPerPage = 5;         //每页显示几条

scope.load = function () {

	var para = {
    	pageNo: scope.bigCurrentPage,
    	pageSize: scope.itemsPerPage,
    	state : scope.state,
    };

  	para = angular.extend(scope.searchform, para);

  	// console.log(para);

	var beforedata = {
		//产品
		'productlist':
		$http({
			'method': 'GET',
			//'url': '/api/ac/wc/productService/wdProductList',
			'url' : '/api/ac/wc/newProductService/wdProductList',
			'params' : para,
		}),

		//类型列表
		'typelist':
		$http({
			'method': 'GET',
			'url': '/api/as/wc/producttype/producttypelist',
		}),
		//栏目列表
		'columnlist':
		$http({
			'method': 'GET',
			'url': '/api/as/wc/configurecolumn/columnlist?state=1',
		}),
	};

	$q.all(beforedata).then(function (res) {
		
		//轮播图列表
		if (res.productlist.data.errcode === 0) {
		} else {
			alert(res.productlist.data.errmsg);
			return;
		}
		//分类列表
		if (res.typelist.data.errcode === 0) {
		} else {
			alert(res.typelist.data.errmsg);
			return;
		}
		//栏目列表
		if (res.columnlist.data.errcode === 0) {
		} else {
			alert(res.columnlist.data.errmsg);
			return;
		}

		console.log(res.productlist.data.data);
		// console.log(res.typelist.data.data);
		// console.log(res.columnlist.data.data);
		
		scope.label['typelist'] = res.typelist.data.data;
		scope.label['typelist'].unshift({ type_name : '未设置类别', type_code: '0' });

		scope.label['columnlist'] = res.columnlist.data.data;
		scope.label['columnlist'].unshift({ column_name : '未设置栏目', column_code: '0' });
		
		typeobj = {};
		for(var i = 0; i < res.typelist.data.data.length; i++){
			var tmp = res.typelist.data.data[i];
			typeobj[tmp.type_code] = tmp;
		}

		columnobj = {};
		for(var i = 0; i < res.columnlist.data.data.length; i++){
			var tmp = res.columnlist.data.data[i];
			columnobj[tmp.column_code] = tmp;
		}
		var results = res.productlist.data.data.results;

		for(var i = 0; i < results.length; i++){
        	var tmp = results[i];
        	// tmp['toppic'] = tmp.top_pic == undefined ? 
        	// 'http://oss.juyouhx.com/weshop/default.jpg' :
        	// tmp.top_pic.split(',')[0];

        	// tmp['toppic'] = tmp.top_pic == undefined ? 
        	// 'http://oss.juyouhx.com/weshop/default.jpg' :
        	// angular.fromJson(tmp.top_pic)[0]['url'];

        	if(angular.isUndefined(tmp.top_pic)){
        		tmp['toppic'] = 'http://oss.juyouhx.com/weshop/default.jpg';
        	}else{
        		try{
        			var tttt = angular.fromJson(tmp.top_pic);
        			console.log(tttt);
        			tmp['toppic'] = tttt[0].url;
        		}catch (err){
        			//console.log(err);
        			tmp['toppic'] = 'http://oss.juyouhx.com/weshop/default.jpg';
        		}
        	}

        	tmp['open'] = true;

        	tmp['back_type_label'] = label.back_type[parseInt(tmp.back_type)];
        	tmp['sms_type_label'] = label.sms_type[parseInt(tmp.sms_type)];
        	tmp['order_num_state_label'] = label.order_num_state[parseInt(tmp.order_num_state)];
        	tmp['order_limit_type_label'] = label.order_limit_type[parseInt(tmp.order_limit_type)];
        	tmp['product_attr_label'] = label.product_attr[parseInt(tmp.product_attr)];
        	tmp['price_type_label'] = label.price_type[parseInt(tmp.price_type)];

        	tmp['start_time_date'] = tmp['start_time'];
        	tmp['end_time_date'] = tmp['end_time'];

        	tmp['tour_date_limit_start_date'] = tmp['tour_date_limit_start'];
        	tmp['tour_date_limit_end_date'] = tmp['tour_date_limit_end'];

        	if((tmp.myproduct == '1') ){
				tmp['product_typename'] = '群盟产品';
			}else{
				tmp['product_typename'] = '自营产品';
			}

			if(angular.isUndefined(tmp.type_code) || tmp.type_code == 0){
				tmp['type_label'] = '未设置类别';
			}else{
				tmp['type_label'] = typeobj[tmp.type_code]['type_name'];
			}

			if(angular.isUndefined(tmp.column_code) || tmp.column_code == 0){
				tmp['column_label'] = '未设置栏目';
			}else{
				tmp['column_label'] = columnobj[tmp.column_code]['column_name'];
			}

			// if(angular.isArray(tmp.ticketlist)){
			// 	if(tmp.ticketlist.length == 1){	//单个门票
			// 		tmp['view_name'] = tmp.ticketlist[0].view_name;
			// 		tmp['t_period'] = tmp.ticketlist[0].periodstart + ' 至 ' + tmp.ticketlist[0].periodend;
			// 	}else if(tmp.ticketlist.length > 1){	//套票
			// 		tmp['view_name'] = '包含 ' + tmp.ticketlist.length + ' 张门票';
			// 		tmp['t_period'] = '查看详情';
			// 	}
			// }

			tmp['opt'] = {
				// 'stock' : '0',
				// 'take_effect' : '0',
				'type' : '0',
				// 'flash' : '0',
				// 'tour' : '0',
				// 'sms' : '0',
				// 'integral' : '0',
				// 'back_type' : '0',
				// 'name' : '0',
			};

			//tmp['cancel_flag'] = '0';


			//----------- 获取产品不能上架的原因 ----------------------//
			var reason = '';
			//1.没有配置门票
			if(tmp.product_attr == '1' && angular.isDefined(tmp.ticketlist))
			{
				if(tmp.ticketlist.length == 0)
				{
					reason = '该产品没有配置门票';
				}
				//2.门票不出票
				else
				{
					var now = new Date();
					var is_available = true;
					for(var j = 0; j < tmp.ticketlist.length; j++){
						var t = tmp.ticketlist[j];
						var end = new Date(t.periodend);
						if(t.is_available == '0' && now < end){
							is_available = false;
							break;
						}
					}

					if(is_available){
						reason = '该产品不出票或者已过期';
					}
				}
			}

			//3.没有配置型号
			if(angular.isDefined(tmp.attrlist))
			{
				if(tmp.attrlist.length == 0)
				{
					reason = '该产品没有配置型号';
				}
				if(tmp.sale_belong != 'qunmeng'){

					for(var j = 0; j < tmp.attrlist.length; j++){
						var m = tmp.attrlist[j];
						if(m.state == '0'){
							continue;
						}
						//票付通
					    if(tmp.sale_belong === 'weshop_piaofutong')
					    {
					        if(!m['sysaffirm_target_goods_supply']
					        || !m['sysaffirm_target_goods_view']
					        || !m['sysaffirm_target_goods_code']){
					        	reason = '该对接产品(票付通)没有设置完整对接信息';
					        	break;
					        }
					    }
					    //居游
					    else if(tmp.sale_belong === 'weshop_juyou')
					    {
					        if(!m['sysaffirm_target_goods_code']){
					        	reason = '该对接产品(居游)没有设置完整对接信息';
					        	break;
					        }
					    }
					    //天时同城（北国）/天时同城（爱旅）
					    else if(tmp.sale_belong === 'weshop_tstc_al'
					         || tmp.sale_belong === 'weshop_tstc_bg')
					    {
					        if(!m['sysaffirm_target_goods_code']){
					        	reason = '该对接产品(天时同城)没有设置完整对接信息';
					        	break;
					        }
					    }
					    //海洋馆
					    else if(tmp.sale_belong === 'weshop_royaloc')
					    {
					        if(!m['sysaffirm_target_goods_code']
					        || !m['sysaffirm_target_goods_back_type']
					        || !m['sysaffirm_target_goods_child_flag']){
					        	reason = '该对接产品(海洋馆)没有设置完整对接信息';
					        	break;
					        }
					    }

					}
				}
			}
			//没有配置型号--end

			
			//console.log('不能上架的原因');
			tmp['unavailableReasons'] = reason;
			//3.门票不出票


			//4.没有可用的场次
			//----------- 获取产品不能上架的原因 ----------------------//





        }

        scope.objs = results;
        scope.bigTotalItems = res.productlist.data.data.totalRecord;
        scope.count = res.productlist.data.data.totalRecord;

	});
};
scope.load();


//排序
scope.asort = function(obj){

	var para = {
		'id' : obj.id,
		'sale_code' : obj.sale_code,
		'asort' : obj.asort,
	}
	updateProduct(para);
};

//上架
scope.up = function(obj){

	var para = {
		'id' : obj.id,
		'sale_code' : obj.sale_code,
		'state' : '1',
	};

	$resource('/api/ac/wc/newProductService/updatesjstate', {}, {}).save(para, function(res){
		console.log(res);
		if (res.errcode !== 0) {
			alert(res.errmsg);
			return;
		}

		scope.load();
		scope.other();
	});
};

//下架
scope.down = function(obj){

	var para = {
		'id' : obj.id,
		'sale_code' : obj.sale_code,
		'state' : '2',
	}
	$resource('/api/ac/wc/newProductService/updatestate', {}, {}).save(para, function(res){
		console.log(res);
		if (res.errcode !== 0) {
			alert(res.errmsg);
			return;
		}
		scope.load();
		scope.other();
	});
};

//删除
scope.delete = function(obj){
	if(!confirm("您确认要删除吗？")) {
        return;
    }
	var para = {
		'id' : obj.id,
		// 'sale_code' : obj.sale_code,
		// 'del_flg' : '1',
	};

	$resource('/api/ac/wc/newProductService/deleteProduct', {}, {}).save(para, function(res){
		console.log(res);
		if (res.errcode !== 0) {
			alert(res.errmsg);
			return;
		}
		scope.load();
		scope.other();
	});

}


//配置海报
scope.setPoster = function (obj) {

	//$resource('/api/ac/wc/productShareService/getshareattr', {}, {}).save({ code: obj.sale_code }, function (res) {
	$resource('/api/ac/wc/newProductShareService/getshareattr', {}, {}).save({ code: obj.sale_code }, function (res) {
		
		console.log(res);

		var pobj = {
			'code': obj.sale_code,
			'title': obj.name,
		};

		if (res.errcode === 0) {
			//没有数据
			if (angular.isUndefined(res.data.share_id)) {

			}
			//有数据
			else {
				pobj['id'] = obj.id;
				if (res.data.img) {
					pobj['share_pic'] = res.data.img;
				}
				if (res.data.qrcode_size) {
					pobj['qrcode_size'] = res.data.qrcode_size;
				}
				if (res.data.width) {
					pobj['width'] = res.data.width;
				}
				if (res.data.height) {
					pobj['height'] = res.data.height;
				}
				if (res.data.nickname_width) {
					pobj['nickname_width'] = res.data.nickname_width;
				}
				if (res.data.nickname_height) {
					pobj['nickname_height'] = res.data.nickname_height;
				}
				if (res.data.nickname_size) {
					pobj['nickname_size'] = res.data.nickname_size;
				}
				if (res.data.nickname_color) {
					pobj['nickname_color'] = res.data.nickname_color;
				}
				if (res.data.nickname_length) {
					pobj['nickname_length'] = res.data.nickname_length;
				}
			}
		}
		else if (res.errcode === 9999) {
			//没数据

		}
		else {
			alert(res.errmsg);
			return;
		}

		var modalInstance = $modal.open({
			template: require('../views/p_poster.html'),
			controller: 'qmposter',
			url: '/qmposter',
			size: 'lg',
			resolve: {
				'obj': function () {
					return pobj;
				},
			}
		});

	});

};

//设置佣金
scope.commission = function(obj) {

	var modalInstance = $modal.open({
		template: require('../views/pop_setcommission.html'),
		controller: 'qmcommission',
		url: '/qmcommission/:code',
		size: 'lg',
		resolve: {
			'p': function () {
				return obj;
			},
		}
	});

	modalInstance.opened.then(function () {// 模态窗口打开之后执行的函数  
		// $scope.load();
	});
	modalInstance.result.then(function (showResult) {
		$scope.load();
	}, function (reason) {
		$scope.load();
		// // click，点击取消，则会暑促cancel  
		// $log.info('Modal dismissed at: ' + new Date());
	});



	// var modalInstance = $modal.open({
	// 	template: require('../../50bussmember/views/commission.html'),
	// 	controller: 'memberlevelcommission',
	// 	url: '/memberlevel/:code',
	// 	size: 'lg',
	// 	resolve: {
	// 		'product': function () {
	// 			return obj;
	// 		},
			
	// 	}
	// });

	// modalInstance.opened.then(function () {// 模态窗口打开之后执行的函数  
	// 	// $scope.load();
	// });
	// modalInstance.result.then(function (showResult) {
	// 	$scope.load();
	// }, function (reason) {
	// 	$scope.load();
	// 	// // click，点击取消，则会暑促cancel  
	// 	// $log.info('Modal dismissed at: ' + new Date());
	// });

}


scope.lala = function(){

	console.log('aaaaa');
	scope.lala111 = scope.lala111 == 1 ? 0 : 1;
};


scope.stock = function(obj){

	obj.opt.stock = obj.opt.stock == '0' ? '1' : '0';

};


scope.changeOpt = function(obj, para){

	obj.cancel_flag = '1';
	obj.opt[para] = obj.opt[para] == '0' ? '1' : '0';

};

scope.setStock = function(obj){
	var para = {
		'id' : obj.id,
		'sale_code' : obj.sale_code,
		'stock_type' : obj.stock_type,
		'current_stock_num' : obj.current_stock_num,
	}
	updateProduct(para, function(){
		obj.opt.stock = obj.opt.stock == '0' ? '1' : '0';
	});
};

scope.setTakeEffectType = function(obj){
	var para = {
		'id' : obj.id,
		'sale_code' : obj.sale_code,
		'take_effect_type' : obj.take_effect_type,
	}
	updateProduct(para, function(){
		obj.opt.stock = obj.opt.stock == '0' ? '1' : '0';
	});
}

scope.setType = function(obj){
	var para = {
		'id' : obj.id,
		'sale_code' : obj.sale_code,
		'type_code' : obj.type_code,
	}
	obj.type_label = typeobj[obj.type_code]['type_name'];
	updateProduct(para, function(){
		obj.opt.type = obj.opt.type == '0' ? '1' : '0';
	});
};

scope.setColumn = function(obj){
	var para = {
		'id' : obj.id,
		'sale_code' : obj.sale_code,
		'column_code' : obj.column_code,
	}
	obj.column_label = columnobj[obj.column_code]['column_name'];
	updateProduct(para, function(){
		obj.opt.type = obj.opt.type == '0' ? '1' : '0';
	});
};

scope.setFlash = function(obj){
	var para = {
		'id' : obj.id,
		'sale_code' : obj.sale_code,
		'flash_state' : obj.flash_state,
		'start_time' : obj.start_time_date.format('YYYY-MM-DD HH:mm') + ':00',
		'end_time' : obj.end_time_date.format('YYYY-MM-DD HH:mm') + ':00',
	}
	console.log(para);
	updateProduct(para, function(){
		obj.opt.flash = obj.opt.flash == '0' ? '1' : '0';
	});
};


scope.setTour = function(obj){
	var para = {
		'id' : obj.id,
		'sale_code' : obj.sale_code,
		'tour_date_type' : obj.tour_date_type,
		'tour_date_limit_start' : obj.tour_date_limit_start_date.format('YYYY-MM-DD'),
		'tour_date_limit_end' : obj.tour_date_limit_end_date.format('YYYY-MM-DD')
	}
	console.log(para);
	updateProduct(para, function(){
		obj.opt.tour = obj.opt.tour == '0' ? '1' : '0';
	});

};

scope.setSms = function(obj){

	var para = {
		'id' : obj.id,
		'sale_code' : obj.sale_code,
		'sms_type' : obj.sms_type,
		'sms_diy' : obj.sms_diy,
	}
	console.log(para);

	updateProduct(para, function(){
		obj.sms_type_label = label.sms_type[parseInt(tmp.sms_type)];
		obj.opt.sms = obj.opt.sms == '0' ? '1' : '0';
	});

};

scope.setIntegral = function(obj){

	var para = {
		'id' : obj.id,
		'sale_code' : obj.sale_code,
		'integral_num' : obj.integral_num,
	}
	console.log(para);

	updateProduct(para, function(){
		obj.opt.integral = obj.opt.integral == '0' ? '1' : '0';
	});

};


scope.setBackType = function(obj){
	var para = {
		'id' : obj.id,
		'sale_code' : obj.sale_code,
		'back_type' : obj.back_type,
	}
	console.log(para);

	updateProduct(para, function(){
		obj.opt.back_type = obj.opt.back_type == '0' ? '1' : '0';
	});
};

scope.setName = function(obj){
	var para = {
		'id' : obj.id,
		'sale_code' : obj.sale_code,
		'name' : obj.name,
	}
	console.log(para);

	updateProduct(para, function(){
		obj.opt.name = obj.opt.name == '0' ? '1' : '0';
	});
};


//更改产品
function updateProduct(para, fun){

	//$resource('/api/ac/wc/productService/createWdProduct', {}, {}).save(para, function(res){
	$resource('/api/ac/wc/newProductService/createProduct', {}, {}).save(para, function(res){
		console.log(res);
		if (res.errcode !== 0) {
			alert(res.errmsg);
			return;
		}
		scope.load();
		if(angular.isDefined(fun)){
			fun();
		}
	});

}


scope.edit = function(obj){

	//$state.go('app.qmnewproduct', {'id' : obj.id});

	var modalInstance = $modal.open({
      template: require('../views/product.html'),
      controller: 'qmnewproduct',
      size: 'lg',
      resolve: {
        id : function(){
            return obj.id;
        }
      }
    });

    modalInstance.result.then(function () {
        //getPlaceList();
        scope.load();
    }, function () {
        scope.load();
    });



};


scope.release = function(obj) {
	console.log('发布');
	//$resource('/api/ac/wc/newProductService/createProduct', {}, {}).save(para, function(res){
	$resource('/api/ac/wc/newProductService/createProductSaleApply', {}, {}).save({
		'id' : obj.id
	}, function(res){
		console.log(res);
		if (res.errcode !== 0) {
			alert(res.errmsg);
			return;
		}
		alert('发布成功，等待审批。')
	});
};

scope.open = function(obj){
	obj['open'] = obj['open'] == true ? false : true;
}


scope.cancel = function(obj){

	angular.forEach(obj.opt, function (value, key) {
	    obj.opt[key] = '0';
	});

	obj.cancel_flag = '0';

};





		}
	};
};

